from django.contrib.auth import authenticate, login
from django.core.paginator import Paginator
from django.http import JsonResponse,HttpResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from App.models import *
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
from django.views import View
from datetime import datetime

# Create your views here.
def home(request):
    tmp = "<h1>Hello</h1>"
    # 查询推荐文章，取前10
    recommand_Articles = Articles.objects.filter(isrecommend=True)[:10]
    # 原创文章查询
    creators = Articles.objects.filter(iscreator=True)[:5]
    links = Friendlink.objects.all()
    print(locals())
    return render(request, 'home.html',locals())

# page 是当前页码
def article_lsit(request,page=1):
    artilces = Articles.objects.all()
    # per_page:每页显示多少条数据
    paginator = Paginator(artilces, 5)
    # 分页对象
    page_obj = paginator.page(page)
    return render(request,"list.html",locals())

class Login_view(View):
    def get(self, request):
        return render(request,"login.html")
    def post(self, request):
        print(request.POST)
        # 获取用户输入的数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('custom_input')
        key = request.POST.get('hash_key')
        print(key,code,username,password)
        # 验证用户名和密码是否正确
        user = authenticate(username=username, password=password)
        print(user,"用户名")
        if user: # 用户名和密码验证成功
            # 根据hash_key查找
            obj = CaptchaCaptchastore.objects.filter(hashkey=key).first()
            print(obj,"验证码")
            if obj and (code.lower() == obj.response) and (datetime.now() < obj.expiration):
                print(111)
                login(request,user)
                # reverse 反向解析
                return redirect(reverse("app:home")) # redirect 跳转到指定页面
            else:
                print(222)
                return render(request,"login.html")
        else:
            print("3333")
            return render(request,"login.html")
# def login(request):
#     print("*"*50)
#     # 生成一个新的hashkey
#     new_key = CaptchaStore.pick()
#     # 生成一个新的图片验证码，返回url
#     res = captcha_image_url(new_key)
#     print(new_key)
#     print(res)
#


def register(request):
    print("****"*10)
    if request.method == "POST":
        # 获取提交的参数
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        print(username,password,email,"用户注册")
        # 验证用户是否存在
        user = User.objects.filter(username=username).first()
        if user is None: # 用户不存在
            User.objects.create_user(username=username, password=password, email=email)
            # redirect("请求地址") 重定向的另外一个页面
            return redirect("/login")
        else:
            # 用户存在
            return render(request, 'register.html',{"msg":"用户名重复"})
    else: #get
        return render(request,"register.html")


def article_detail(request,tid):
    print(tid)
    # get根据主键查询 pk代表主键
    article = Articles.objects.get(pk=tid)
    # 查询文章评论
    comments = Comments.objects.filter(tid=tid)
    # 查询评论者的名称
    for item in comments:
        item.author = User.objects.get(pk=item.uid)
        print(item)
    return render(request,"content.html",locals())


def generate_captcha(request):
    # 生成一个新的hashkey
    new_key = CaptchaStore.pick()
    # 生成一个新的图片验证码，返回url
    res = captcha_image_url(new_key)
    print(new_key,res)
    return JsonResponse({
        'image_url': res,
        "key": new_key
    })


def verify_code(request):
    from datetime import datetime
    if request.method == "POST":
        print(request.POST)
        # 获取用户输入的数据
        code = request.POST.get('custom_input')
        key = request.POST.get('hash_key')
        # 根据hash_key查找
        obj = CaptchaCaptchastore.objects.filter(hashkey=key).first()
        if obj and (code.lower() == obj.response) and (datetime.now()<obj.expiration):
            return HttpResponse("ok")
        else:
            return HttpResponse("error")
    return render(request,"yzm.html")


def remark_article(request):
    tid = request.POST.get('tid')
    comment = request.POST.get('comment')
    print(tid,comment)
    # 把评论写回数据库
    # article = Articles.objects.get(pk=tid)
    # obj = Comments(content=comment,tid=article,uid=request.user)
    obj = Comments(content=comment,tid=tid,uid=request.user.id)
    obj.save()
    return redirect(reverse("app:article_detail", args=[tid]))